package com.jch.demo.cd.interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;

import javax.servlet.http.HttpServletResponse;

/**
 * 跨域处理拦截器
 *
 * @author 迩道
 */
public class CrossInterceptor implements Interceptor {

  @Override
  public void intercept(Invocation inv) {
    //注解声明在类上
    Cross cross = inv.getController().getClass().getAnnotation(Cross.class);
    if (cross != null) {
      handler(inv.getController().getResponse());
      inv.invoke();
      return;
    }
    //注解声明在方法上
    cross = inv.getMethod().getAnnotation(Cross.class);
    if (cross != null) {
      handler(inv.getController().getResponse());
      inv.invoke();
      return;
    }
  }

  /**
   * 处理response
   * @param response
   */
  private void handler(HttpServletResponse response) {
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET");
    response.setHeader("Access-Control-Max-Age", "3600");
    //response.setHeader("Access-Control-Allow-Headers",
    //  "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
    response.setHeader("Access-Control-Allow-Headers", "*");
  }


}
